<?php
/* --------------------------------------------------------------
   write_sql_log.inc.php 2011-09-08 gambio
   Gambio GmbH
   http://www.gambio.de
   Copyright (c) 2011 Gambio GmbH
   Released under the GNU General Public License (Version 2)
   [http://www.gnu.org/licenses/gpl-2.0.html]
   --------------------------------------------------------------
*/
?><?php

include_once(DIR_FS_CATALOG . 'system/core/StopWatch.inc.php');
include_once(DIR_FS_CATALOG . 'gm/classes/FileLog.php');

function write_sql_log($p_query)
{
	$t_log_created = false;

	if(
		!defined('APPLICATION_RUN_MODE')
			||
		!defined('LOG_SQL_FRONTEND')
			||
		!defined('LOG_SQL_BACKEND')
			||
		(APPLICATION_RUN_MODE == 'frontend' && LOG_SQL_FRONTEND == 'true')
			||
		(APPLICATION_RUN_MODE == 'backend' && LOG_SQL_BACKEND == 'true')
	)
	{
		if(strtoupper(substr(ltrim($p_query), 0, 6)) != 'SELECT' 
				&& strtoupper(substr(ltrim($p_query), 0, 11)) != 'SHOW TABLES'
				&& strpos(strtolower($p_query), 'set products_viewed = products_viewed') === false
				&& preg_match('/\s*(INSERT\s+INTO|UPDATE|DELETE\s+FROM)\s+(whos_online|magnalister_session|magnalister_selection|`magnalister_selection`|gm_counter_page|gm_counter_ip)/i', $p_query) === 0)
		{
			if(isset($GLOBALS['coo_stop_watch_array']))
			{
				if(!is_object($GLOBALS['coo_stop_watch_array']['sql_queries']))
				{
					$GLOBALS['coo_stop_watch_array']['sql_queries'] = new StopWatch();
				}

				$GLOBALS['coo_stop_watch_array']['sql_queries']->start();
			}

			$coo_sql_log = new FileLog('sql_queries');

			$t_log_info = 'URL: ' . $_SERVER['REQUEST_URI'] . "\n";
			if(isset($_SESSION['customer_id']))
			{
				$t_log_info .= 'customers_id: ' . $_SESSION['customer_id'] . "\n";
			}
			$t_log_info .= 'Time: ' . date('d.m.Y H:i:s') . "\n";
			$t_log_info .= 'IP: ' . $_SERVER['REMOTE_ADDR'] . "\n";
			$t_log_info .= "Query:\n" . trim($p_query);
			$t_log_info .= "\n\n================================================================================\n\n";

			$coo_sql_log->write($t_log_info);

			$t_log_created = true;

			if(isset($GLOBALS['coo_stop_watch_array']))
			{
				$GLOBALS['coo_stop_watch_array']['sql_queries']->stop();
			}
		}
	}

	return $t_log_created;
}

?>